<?php

namespace App\Http\Controllers\Common;

use App\Http\Controllers\Common\MediaRequest;
use App\Http\Controllers\Controller;
use App\Models\File;
use Illuminate\Filesystem\Filesystem;
use App\Http\Controllers\Common\FileRequest as FileRequests;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Intervention\Image\Facades\Image;
use App\Models\File as FileModel;
use DB, Config, Validator, Session;

class FileController extends Controller
{

    //获取文件
    public function obtain(Request $request, FileModel $fileModel)
    {
        ini_set('memory_limit', '20M');
        try {
            $path = $fileModel->path;
            $url = (((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://') . env('DOMAIN_NAMES', $_SERVER['SERVER_NAME']);
            $url = $url.'/storage/';
            $path = str_replace($url,'',$path);
            if (Storage::exists($path)) {
                $mimes = [
                    'image/jpeg',
                    'image/png',
                    'image/gif',
                ];

                //如果不是图片格式则返回
                if ( !in_array($fileModel->mime_type, $mimes)) {

                    return redirect("/storage/{$path}");
                }


                //获取剪切参数 默认0
                $width  = abs(intval($request->input('w', 0)));
                $height = abs(intval($request->input('h', 0)));
                //没有指定高宽 返回原图
                if ( !$width && !$height) {
                    return redirect("/storage/{$path}");
                }

                //分解文件夹与后缀
                list($directory, $extension) = explode('.', $fileModel->filename);
                //新文件名称
                $newFileName = md5($fileModel->filename . md5($width) . md5($height)) . ".{$extension}";

                //获取文件路径
                list($filePath) = explode('.', $path);

                //新文件绝对路径
                $newFilePath = Storage::path($filePath) . "/{$newFileName}";


                $date = substr($fileModel->path, 0, strrpos($path, '/'));

                //新文件相对路径
                $newFileRelativePath = "storage/{$date}/{$directory}/{$newFileName}";


                //如果同样的大小之前后剪切返回之前的内容
                if (Storage::exists($newFilePath)) {
                    return redirect($newFileRelativePath);
                };


                //获取被剪切的图片
                $image = Image::make(Storage::path($path));

                //获取宽高比例
                if ($width) {
                    $widthRatio = bcdiv($image->width(), $width, 1);
                } else {
                    $widthRatio = 0;
                    $width      = $height;
                }
                if ($height) {
                    $heightRatio = bcdiv($image->height(), $height, 1);
                } else {
                    $heightRatio = 0;
                    $height      = $width;
                }

                //最小比例
                $minRatio = min($heightRatio, $widthRatio);

                if (($minRatio === $width && $width) || ((bool)$width && !$height)) {

                    $image->resize(
                        intval($image->width() / 1.5), null, function ($constraint) {
                        $constraint->aspectRatio();
                    }
                    );
                } elseif (($minRatio === $height && $width) || ((bool)$height && !$width)) {

                    $image->resize(
                        null, intval($image->height() / 1.5), function ($constraint) {
                        $constraint->aspectRatio();
                    }
                    );
                }

                $image->fit($width, $height);

                $fileSystem = new Filesystem();
                //如果没有对应的文件夹 就创建文件夹
                if ( !$fileSystem->exists(Storage::path($filePath))) {
                    $fileSystem->makeDirectory(Storage::path($filePath));
                }
                //保存对应的文件
                $image->encode($extension)->save($newFilePath);
                return redirect($newFileRelativePath);

            }

        } catch (\Exception $exception) {
            report($exception);
        }

        return response('', 400);
    }

    /**
     * 上传文件
     * URL POST:/api/file/upload
     * @param FileRequest $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function upload(FileRequests $request)
    {
        $identity = $request->input('identity', 1);
        $file = $request->file('file');
        $fileType = $file->getClientMimeType();
        if ($fileType != 'image/gif' && $fileType != 'image/jpeg' && $fileType != 'image/jpg' && $fileType != 'image/png' && $fileType != 'image/x-icon') {
            return [
                'code'   => 400,
                'status' => false,
                'msg'    => '请上传图片类文件'
            ];
        }

        $res = upload($request, $identity);
        if ($res) {
            return [
                'code'   => 200,
                'msg'    => '上传成功',
                'file'   => $res['id'],
                'img_path' => $res['path']
            ];
        }

        return [
            'code'   => 400,
            'msg'    => '上传失败'
        ];
    }

    /**
     * 上传文件(打包文件)
     * URL POST:/api/file/uploadZip
     * @param FileRequest $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function uploadZip(FileRequests $request)
    {
        $identity = $request->input('identity', 1);
        $file=$request->file('file');
        // 文件mime
        $fileType=$file->getClientMimeType();

        $id = upload($request, $identity);

        if ($id) {
            return [
                'code'   => 200,
                'msg'    => '上传成功',
                'file'   => $id
            ];
        }

        return [
            'code'   => 400,
            'msg'    => '上传失败'
        ];
    }


    /**
     * 删除文件
     * POST:/api/v1/file/delete
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws
     */
    public function deleteFile(Request $request)
    {
        if ( !isset($request['id']) || $request['id'] < 1) {
            return $this->error('请选择文件');
        }

        $file = File::find($request['id']);

        if ( !$file) {
            return $this->error('文件不存在');
        }

        // 删除图片文件
        DB::beginTransaction();
        try {
            if ( !Storage::exists($file->path)) {
                return $this->error('文件丢失');
            }

            $re = Storage::delete($file->path);
            if ($re) {
                // 删除数据库文件
                File::where('id', $request['id'])->delete();
            }
            DB::commit();
        } catch (\Exception $e) {
            DB::rollback();
            return $this->error($e->getMessage());
        }

        return $this->success([], '删除成功');
    }

    /**
     * 上传视频（手机端）
     * URL POST:/api/file/uploadMedia
     * @param MediaRequest $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function upload_media(MediaRequest $request)
    {
        $id = upload_media($request);
        if ($id) {
            return [
                'code'     => 200
                , 'status' => true
                , 'msg'    => '上传成功'
                , 'data'   => ['id' => $id]
            ];
        }
        return [
            'code'     => 400
            , 'status' => false
            , 'msg'    => '文件上传失败'
        ];
    }

}


